package service

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"micro-chat/config"
	"micro-chat/internal/model"
	"micro-chat/internal/request"
	"net/http"
	"strconv"
	"time"
)

func SendSms(c *gin.Context) {
	var req request.SendSmsForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "验证失败",
		})
		return
	}

	get := config.RDB.Get(config.Ctx, "sendSmsNum"+req.Phone)

	if get.Val() == "3" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "一分钟内只能发送三次",
		})
		return
	}

	//短信
	code := strconv.Itoa(rand.Intn(900000) + 100000)

	var sms model.SmsVerify
	sms.Phone = req.Phone
	err := sms.FindPhone()
	if err != nil {
		return
	}

	if sms.Id == 0 {
		sms = model.SmsVerify{
			Code:       code,
			SendCount:  0,
			ExpireTime: (time.Now().Add(time.Minute * 15)),
		}
		err = sms.AddSms()
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    100000,
				"message": "发送失败",
				"data":    err.Error(),
			})
			return
		}

	} else {
		if sms.SendCount == 3 {
			sms.SendCount = 0
		}

		sms.Code = code
		sms.SendCount += sms.SendCount
		err = sms.UpdateSms()
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    100000,
				"message": "发送失败",
				"data":    err.Error(),
			})
			return
		}
	}

	//短信发送
	//pkg.SendSms(req.Phone, code)

	//缓存
	config.RDB.Set(config.Ctx, "sendSms"+req.Phone+req.Source, code, time.Minute*15)
	//次数
	//config.RDB.Set(config.Ctx, "sendSmsNum"+req.Phone, 0, time.Minute)
	config.RDB.Incr(config.Ctx, "sendSmsNum"+req.Phone)
	config.RDB.Expire(config.Ctx, "sendSmsNum"+req.Phone, time.Minute)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "发送成功",
	})

}
